package com.yz.dba.service;

import com.yz.common.utils.JdbcUtils;
import com.yz.dba.thread.ThreadCoreTest;
import com.yz.dba.thread.ThreadTest;
import com.yz.common.pojo.Database;
import com.yz.common.pojo.DbLink;
import com.yz.common.pojo.Task;
import com.yz.dba.mapper.DbaMapper;
import com.yz.dba.vo.DatabaseInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 段成
 * @date 2019/12/5 - 10:22
 */
@Service
public class DbaService {
    @Autowired
    private DbaMapper dbaMapper;

    public List<DbLink> getLinkName() {
        return dbaMapper.getLinkName();
    }

    public List<Database> getDatabaseByLinkId(Integer linkId) {
        return dbaMapper.getDatabaseByLinkId(linkId);
    }

    public List<String> getTablesByDatabaseId(Integer databaseId) {
        String databaseName = dbaMapper.getDatabaseNameByDatabaseId(databaseId);
        return dbaMapper.getTablesByDatabaseName(databaseName);
    }

    public List<String> getfieldNamesByDatabaseNameAndTableName(Integer databaseId, String tableName) {
        Map map = this.generateDatabaseMap(databaseId);
        String databaseName = dbaMapper.getDatabaseNameByDatabaseId(databaseId);


        ArrayList<String> fields = JdbcUtils.getfieldNamesByDatabaseNameAndTableName(map, databaseName, tableName);

        return fields;
    }

    public void dataMigration(Task task) {
        dbaMapper.updateTaskStatus(task.getId(),5);
        //获取数据库基本四项  字符串拼接
        Map sourceMap = this.generateDatabaseMap(task.getSourceDatabaseId());
        Map targetMap = this.generateDatabaseMap(task.getTargetDatabaseId());

        //开启主线程
        ThreadTest threadTest = new ThreadTest(sourceMap, targetMap, task.getSourceTableName(),task.getTargetTableName(),task.getTaskNumber(),task.getFieldNames());
        new Thread(threadTest).start();
        dbaMapper.updateTaskStatus(task.getId(),4);
    }

    /**
     * 拼接url
     * @param databaseInfo
     * @return
     */
    public String spliceUrl(DatabaseInfo databaseInfo){
        StringBuffer url = new StringBuffer();
        if("mysql".equals(databaseInfo.getDbTypeName())){
            url.append("jdbc:mysql://");
            url.append(databaseInfo.getIp());
            url.append(":");
            url.append(databaseInfo.getPort());
            url.append("/");
            url.append(databaseInfo.getDatabaseName());
            url.append("?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&serverTimezone=UTC");
        }
        if("Oracle".equals(databaseInfo.getDbTypeName())){
            //等待补全
        }
        return url.toString();
    }

    /**
     * 生成数据库map  其中调用了本类中的spliceUrl方法
     * @param databaseId
     * @return
     */
    public Map generateDatabaseMap(Integer databaseId){

        DatabaseInfo databaseInfo = dbaMapper.getDatabaseInfo(databaseId);
        String url = this.spliceUrl(databaseInfo);


        HashMap<String, String> map = new HashMap<>();
        map.put("driver", databaseInfo.getDriver());
        map.put("url", url);
        map.put("username", databaseInfo.getUsername());
        map.put("pass", databaseInfo.getPass());
        return map;
    }


    @Transactional
    public void commitTask(Task task) {
        Integer userId = dbaMapper.findUserIdByUsername(task.getSubmitName());
        String sourceDatabaseName = dbaMapper.findDatabaseNameById(task.getSourceDatabaseId());
        String targetDatabaseName = dbaMapper.findDatabaseNameById(task.getTargetDatabaseId());

        task.setTaskTypeName(dbaMapper.getTaskTypeNameByTypeId(task.getTaskType()));
        task.setSourceDatabaseName(sourceDatabaseName);
        task.setTargetDatabaseName(targetDatabaseName);
        task.setSubmitId(userId);
        task.setSubmitName(task.getSubmitName());
        task.setDstatus(1);
        //任务审核者暂时为空

        //任务编号
        task.setTaskNumber(this.GenerateTaskNumber());
        //任务类型编号
        //任务类型名称
        task.setTaskTypeName(dbaMapper.getTaskTypeNameByTypeId(task.getTaskType()));

        //任务状态默认为2 未审核
        task.setStatus(2);
        //创建任务的时间
        task.setCdate(new Date());
        //审核日期
        task.setLevel(1);
        dbaMapper.commitTask(task);
    }

    //生成任务编号
    public String GenerateTaskNumber(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        return simpleDateFormat.format(new Date());
    }

    public Task findTaskById(Integer taskId) {
        return dbaMapper.findTaskById(taskId);
    }

    public List<Task> findTask(String username) {
        Integer userId = dbaMapper.findUserIdByUsername(username);
        return dbaMapper.findTask(userId);
    }

    public int deleteTaskById(Integer taskId) {
        return dbaMapper.deleteTaskById(taskId);
    }

    public Database getDatabaseLinkIdById(Integer targetDatabaseId) {
        return dbaMapper.getDatabaseLinkIdById(targetDatabaseId);
    }

    public DbLink getDbLinkByLinkId(Integer linkId) {
        return dbaMapper.getDbLinkByLinkId(linkId);
    }

    public void dataMigrationCore(Task task) {
        Map sourceMap = this.generateDatabaseMap(task.getSourceDatabaseId());
        Map targetMap = this.generateDatabaseMap(task.getTargetDatabaseId());
        //开启主线程
        ThreadCoreTest threadTest = new ThreadCoreTest(sourceMap,targetMap, task.getSourceTableName(),task.getTargetTableName(),task.getTaskNumber(),task.getCoreFields());
        new Thread(threadTest).start();
        dbaMapper.updateTaskStatus(task.getId(),4);
    }

    public List<String> getCoreFields() {
        List<Map> list = dbaMapper.getCoreFields();
        List<String> arrayList = new ArrayList<>();
        for (Map map : list) {
            arrayList.add((String) map.get("Field"));
        }
        return arrayList;
    }
}
